package com.zyh.server.controller;

import com.zyh.server.config.Constant;
import com.zyh.server.entity.User;
import com.zyh.server.service.UserService;
import com.zyh.server.utils.R;
import com.zyh.server.utils.RedisUtil;
import com.zyh.server.utils.UUIDUtil;
import com.zyh.server.vo.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zyh
 * @Date: 2024-11-12-11:27
 * @Description
 */
@Slf4j
@Tag(name = "用户模块")
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtil redisUtil;

	/**
	 * controller层用户登录方法
	 *
	 * @param loginVO 前端传入的用户数据
	 *
	 * @return 返回统一结果集
	 */
	@Operation(summary = "用户登录")
	@Parameters({@Parameter(name = "loginVO", description = "自定义封装登录参数")})
	@PostMapping("/login")
	public R getUserByUsernameAndPassword(@RequestBody LoginVO loginVO) {
		log.info("正在请求UserController-->getUserByUsernameAndPassword()，请求参数{}", loginVO);
		R r = userService.findUserByUsernameAndPassword(loginVO);
		log.info("正在请求UserController-->getUserByUsernameAndPassword()，返回给前端的数据{}", loginVO);
		// 登录成功，生成唯一标识token
		if (r.isSuccess()) {
			String token = UUIDUtil.getUuid();
			redisUtil.saveObj(Constant.REDIS_TOKEN_PREFIX + token, r.getData(), Constant.REDIS_TOKEN_EXPIRE);
			Map<String, Object> map = new HashMap<>();
			map.put("token", token);
			map.put("user", r.getData());
			return R.ok("登录成功！").setData(map);
		}
		return r;
	}

	@Operation(summary = "用户退出")
	@Parameters({@Parameter(name = "token", description = "用户唯一标识")})
	@GetMapping("/logout")
	public R logout(@RequestHeader("token") String token) {
		// 从redis中删除token
		redisUtil.deleteObj(Constant.REDIS_TOKEN_PREFIX + token);
		return R.ok("退出成功！");
	}

	@Operation(summary = "批量生成用户名和密码")
	@GetMapping("/createUser")
	public R createUser() {
		for (int i = 0; i < 100; i++) {
			User user = new User();
			user.setUsername("zyh" + i);
			user.setPassword("37cbc2f0be822f5ab96485ac11f3dc98");
			String token = UUIDUtil.getUuid();
			// 存入数据库中
			userService.save(user);
			// 存入redis中
			redisUtil.saveObj(Constant.REDIS_TOKEN_PREFIX + token, user, 60 * 24);
			addUserToTxt(user.getUsername(), token);
		}
		return R.ok("生成用户成功！");
	}


	/**
	 * 把用户名和token写入txt文件
	 *
	 * @param username
	 * @param token
	 */
	private void addUserToTxt(String username, String token) {
		try {
			String arr = username + "," + token;
			java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("D:/users.txt"), true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(arr + "\r\n");
			bw.flush();
			bw.close();
			fw.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Operation(summary = "更改用户信息")
	@Parameters({@Parameter(name = "user", description = "用户信息对象")})
	@PutMapping("/updateUserInfo")
	//
	public R editUserInfo(@RequestHeader("token") String token, @RequestBody User user) {
		log.info("获取到的token-->{}", user);
		log.info("获取到的user-->{}", user);
		return userService.modifyUserInfo(token, user);
	}
}
